package com.specificgroup.jira.plugin.acpro.action;

import com.atlassian.plugin.webresource.WebResourceManager;
import com.specificgroup.jira.plugin.acpro.model.ReviewData;
import com.specificgroup.jira.plugin.acpro.model.Settings;
import com.specificgroup.jira.plugin.acpro.service.ReviewBuilder;
import com.specificgroup.jira.plugin.acpro.session.SessionTempData;
import com.specificgroup.jira.plugin.acpro.session.SessionUtil;

/**
 *
 * @author Ivan Holub
 */
public class ReviewAction extends AcproActionSupport {

    private static final String NEXT_ACTION = "AcproImport.jspa";

    private static final String RESOURCE_KEY = "com.specificgroup.jira.plugin.acpro.jira-acpro-plugin:acpro-resource-js-review";

    private ReviewData reviewData;

    private ReviewBuilder reviewBuilder;

    private WebResourceManager webResourceManager;

    private String confirmation;

    public void setConfirmation(String confirmation) {
        this.confirmation = confirmation;
    }

    public ReviewAction(ReviewBuilder reviewBuilder, WebResourceManager webResourceManager) {
        this.reviewBuilder = reviewBuilder;
        this.webResourceManager = webResourceManager;
    }

    public ReviewData getReviewData() {
        return reviewData;
    }

    @Override
    public String doDefault() throws Exception {
        if (!hasPermissions()) {
            return PERMISSION_VIOLATION_RESULT;
        }

        webResourceManager.requireResource(RESOURCE_KEY);

        Settings settings = SessionUtil.getSettings();
        reviewData = reviewBuilder.getReviewData(settings);

        SessionTempData sessionTempData = SessionUtil.getSessionTempData();
        sessionTempData.setReviewData(reviewData);

        return super.doDefault();
    }

    @Override
    protected String doExecute() throws Exception {
        if (!hasPermissions()) {
            return PERMISSION_VIOLATION_RESULT;
        }
        
        String redirect = getRedirect(NEXT_ACTION);
        return redirect;
    }

    @Override
    protected void doValidation() {

        if (confirmation == null) {

            webResourceManager.requireResource(RESOURCE_KEY);

            SessionTempData sessionTempData = SessionUtil.getSessionTempData();
            reviewData = sessionTempData.getReviewData();

            addErrorMessage(getText("confirmation.error"));
        }

        super.doValidation();
    }
}
